// dart_exception_handling_demonstration.dart
// 演示Dart异常处理机制

class OutOfLlamasException implements Exception {
  final String message;
  const OutOfLlamasException([this.message = "No more llamas!"]);

  @override
  String toString() => "OutOfLlamasException: $message";
}

class AnimalFarm {
  int llamaCount = 0;

  void breedMoreLlamas() {
    if (llamaCount <= 0) {
      throw OutOfLlamasException("Need to buy more llamas first!");
    }
    // 模拟繁殖逻辑
    llamaCount *= 2;
  }

  void buyMoreLlamas() {
    llamaCount += 5;
    print("Bought 5 new llamas! Total: $llamaCount");
  }
}

void misbehave() {
  try {
    dynamic foo = true;
    print(foo++); // 触发类型错误
  } catch (e) {
    print('misbehave() 部分处理了 ${e.runtimeType}');
    rethrow; // 重新抛出异常
  } finally {
    print("misbehave() 的清理操作完成");
  }
}

void assertExamples() {
  String? text;
  int number = 150;
  String urlString = "http://example.com";

  // 解决方案：强制允许空值比较
  assert(() {
    return text != null;
  }(), "文本不能为空");

  // 或者使用 ?. 操作符替代
  assert(text?.isNotEmpty ?? false, "文本不能为空");

  // 其他断言保持不变
  assert(number < 100, "数值超过限制");
  assert(urlString.startsWith('https'), "URL必须以https开头：$urlString");
}

void main() {
  var farm = AnimalFarm();

  // 基础异常处理
  try {
    farm.breedMoreLlamas(); // 初始llamaCount为0，会抛出异常
  } on OutOfLlamasException {
    print("捕获到 OutOfLlamasException，执行处理...");
    farm.buyMoreLlamas();
  } catch (e, stackTrace) {
    print("捕获到通用异常: $e");
    print("堆栈跟踪: $stackTrace");
  } finally {
    print("基础操作完成，当前llama数量: ${farm.llamaCount}");
  }

  // 多重捕获示例
  try {
    misbehave();
  } catch (e) {
    print("main() 最终处理了 ${e.runtimeType}");
  }

  // 断言测试（取消注释以测试）
  /*
  try {
    assertExamples();
  } catch (e) {
    print("断言触发: $e");
  }
  */
}
